#include <Python.h>
#include <iostream>
#include <direct.h>
#include <mirai.h>
#include <string>
using namespace std;

bool _search()
{
	// 初始化Python环境
	Py_Initialize();
	// 判断初始化是否成功  
	if (!Py_IsInitialized())
	{
		cout << "Initialize failed ..." << endl;
		// 关闭 Python 脚本解释器，释放内存。
		Py_Finalize();
	}
	cout << "初始化成功" << endl;
	PyObject* pModule = NULL;
	PyObject* pFunc = NULL;
	PyObject* pArg = NULL;

	// 添加模块路径
	PyRun_SimpleString("import sys");
	PyRun_SimpleString("sys.path.append('E:/学习相关/C++/testCode/mirai-cpp-template/src')");
	cout << "添加模块路径" << endl;
	// 导入模块
	pModule = PyImport_ImportModule("search_rank");
	if (!pModule) // 检查模块是否导入成功
	{
		cout << "Python file import failed ..." << endl;
		Py_Finalize();
	}
	else
	{
		cout << "导入模块" << endl;
		// 导入函数
		pFunc = PyObject_GetAttrString(pModule, "appapi_ranking"); //python 脚本里的函数名
		if (!pFunc) // 检查函数是否导入成功
		{
			cout << "Function import failed ..." << endl;
			Py_Finalize();
		}
		cout << "导入函数" << endl;
		//PyObject* pParams = Py_BuildValue("(i)", 1);
		cout << "通过" << endl;
		//char* result;

		cout << "调用函数" << endl;
		pArg = PyEval_CallObject(pFunc, NULL); // 调用函数
		cout << "调用函数完成" << endl;
		//获取结果，python类型转换为C++类型。
		//PyArg_Parse(pArg, "s", &result);
		
		//cout << result << endl;
		if (pArg)
		{
			Py_DECREF(pArg);
			cout << "pArg释放成功" << endl;
		}
		if (pFunc)
		{
			Py_DECREF(pFunc);
			cout << "pFunc释放成功" << endl;
		}
		if (pModule)
		{
			Py_DECREF(pModule);
			cout << "pModule释放成功" << endl;
		}
		Py_Finalize();
		cout << "Py_Finalize成功" << endl;
		return true;
	}
	Py_Finalize();
}